package org.huzhp.gateway.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;

/**
 * @Description: 调式拦截器
 * @Author: huzp
 * @CreateDate: 2020/3/13 13:02
 * @Version: 1.0
 */
public abstract class CommonGatewayFilterFactory<C> extends AbstractGatewayFilterFactory<C> {

    protected static final Logger logger = LoggerFactory.getLogger(CommonGatewayFilterFactory.class);

    protected static final String KONG = "\n\r  ";
    protected static final String POST_BODY = "POST_BODY";

    protected static final String DEBUG_REQUESTID_HEADER = "Gateway-RequestId";

    protected static final List<String> suffixs = Arrays.asList(".css", ".js", ".gif", ".jpg", ".png", ".ico", ".map");

    public CommonGatewayFilterFactory(Class<C> configClass) {
        super(configClass);
    }

    protected void responseCallBack(C c, ServerWebExchange exchange) {
        logger.debug("配置参数信息:{}", c.toString());
        setResponeHeader(exchange.getRequest(), exchange.getResponse());
    }

    protected void setResponeHeader(ServerHttpRequest request, ServerHttpResponse response) {
        response.getHeaders().set(DEBUG_REQUESTID_HEADER, request.getId());
    }

    public boolean checkStaticResource(boolean need, ServerHttpRequest request) {
        return need ? isStaticResources(request) : false;
    }

    public boolean isStaticResources(ServerHttpRequest request) {
        String url = request.getURI().getPath();
        return suffixs.stream().filter(s -> url.endsWith(s)).count() > 0;
    }


}
